<template>
  <div class="search-component">
    <GapedRow gap="large">
      <GapedRow gap="middle">
        <GapedRow gap="middle">
          <GapedRow>
            <span>日期范围</span>
            <el-date-picker
              v-if="showTime"
              v-model="selectedTime"
              type="datetime"
              placeholder="选择日期时间"
              style="width: 200px"
            />
          </GapedRow>
          <el-slider
            v-if="showTime"
            v-model="timeRange"
            :min="1"
            :max="60"
            :step="1"
            style="width: 100px"
          />
          <el-select
            v-if="showTime"
            v-model="timeUnit"
            placeholder="选择单位"
            style="width: 130px"
          >
            <el-option
              v-for="item in timeUnitOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-tooltip
            v-if="showTime"
            effect="dark"
            :content="tooltipContent"
            placement="top"
          >
            <el-icon><InfoFilled /></el-icon>
          </el-tooltip>
        </GapedRow>
        <el-select
          v-model="selectedBusiness"
          placeholder="选择业务"
          clearable
          filterable
          style="width: 200px"
        >
          <el-option
            v-for="item in apiStore.apiStates.getBusinessItems.data"
            :key="item.name"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </GapedRow>
      <slot name="extra"> </slot>
    </GapedRow>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { GapedRow } from '@/core/components'
import useApi from '@/core/apiStore'
import { InfoFilled } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
//import { SEARCH_EVENT, BUSINESS_CHANGED_EVENT } from '@/constants/event'

const SEARCH_EVENT = 'search'
const BUSINESS_CHANGED_EVENT = 'businessChanged'

withDefaults(
  defineProps<{
    showTime?: boolean
  }>(),
  {
    showTime: true,
  }
)

const apiStore = useApi()

const emit = defineEmits<{
  (e: typeof SEARCH_EVENT, timeRange: [string, string], business: string): void
  (e: typeof BUSINESS_CHANGED_EVENT, name: string): void
}>()

const selectedTime = ref(new Date())
const timeRange = ref<number>(30) // 默认30秒
const timeUnit = ref<string>('s') // 默认秒
const selectedBusiness = ref<string>('')

const timeUnitOptions = [
  { label: '秒', value: 's' },
  { label: '分', value: 'm' },
  { label: '小时', value: 'h' },
]

const tooltipContent = computed(() => {
  if (!selectedTime.value) return ''
  const unitText =
    timeUnitOptions.find(item => item.value === timeUnit.value)?.label || ''
  return `查询${formatDate(selectedTime.value)}前后${timeRange.value}${unitText}的日志数据`
})

const formatDate = (date: Date) => {
  return date.toLocaleString()
}

// 计算时间范围
const computedTimeRange = computed(() => {
  if (!selectedTime.value) return ['', '']

  let multiplier = 1000 // 默认秒
  if (timeUnit.value === 'm') {
    multiplier = 1000 * 60
  } else if (timeUnit.value === 'h') {
    multiplier = 1000 * 60 * 60
  }

  const date = new Date(selectedTime.value)
  const startTime = new Date(date.getTime() - timeRange.value * multiplier)
  const endTime = new Date(date.getTime() + timeRange.value * multiplier)

  return [
    dayjs(startTime).format('YYYY-MM-DD HH:mm:ss'),
    dayjs(endTime).format('YYYY-MM-DD HH:mm:ss'),
  ]
})

// 监听业务选择变化
watch(selectedBusiness, newValue => {
  if (newValue) {
    emit(BUSINESS_CHANGED_EVENT, newValue)
  }
})

// 监听搜索条件变化
watch([selectedTime, timeRange, timeUnit, selectedBusiness], () => {
  if (selectedTime.value && selectedBusiness.value) {
    emit(SEARCH_EVENT, {
      timeRange: computedTimeRange.value,
      business: selectedBusiness.value,
    })
  }
})

onMounted(async () => {
  await apiStore.getBusinessItems()
  emit(SEARCH_EVENT, {
    timeRange: computedTimeRange.value,
    business: selectedBusiness.value,
  })
})
</script>

<style scoped>
.search-component {
  display: flex;
  gap: 20px;
  align-items: center;
}

.time-range-container {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 400px;
}
</style>
